package com.ojoin.trade.common_core.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ojoin.trade.common.CallBack;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.SpringUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.BaseEntity;
import com.ojoin.trade.common.web.domain.Dict;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.DictService;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.supplyloan_core.constdef.RenewTypeDesc;

/**
 * 通用续签简单流程
 * @author huanggc
 *
 */
@Controller
@RequestMapping("renew")
public class CommonRenewController extends SimpleBaseController {

	private static final Logger log=LoggerFactory.getLogger(CommonRenewController.class);
	
	@Autowired
	private DictService dictService;
	
	@Autowired
    private TbUploadFileService tbUploadFileService;
	
	
	@ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(HttpServletRequest request){
		SessionUser uservo = CommonUtils.getSessionUser(request);
		
		Dict queryDict=new Dict();
		queryDict.setCreateBy(new User(uservo.getId()));
		queryDict.setType("renew");
		queryDict.setDelFlag(BaseEntity.DEL_FLAG_AUDIT);
		
		
		List<Dict> dicts=dictService.queryList(queryDict);
		List<String> ret=CommonUtils.extractToList(dicts, "value");
		
		return new Result(Result.Status.OK,ret);
	}
	
	/**
	 * @param fileType 枚举类型
	 * @param renewType 类型标示或id
	 * @throws IOException
	 */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile( HttpServletRequest request, HttpServletResponse response,
    		@RequestParam(value = "uploadFile") MultipartFile file,
    		RenewTypeDesc fileType,
    		String expiredDate,
    		String renewType
    		) throws IOException{
    	
		SessionUser sessionUser = CommonUtils.getSessionUser(request);
		int joinuserid = sessionUser.getId();
		
		Result res = CommonUtils.getPathUploadedFile(request, response, file, fileType.getBusiDir());
        if (Status.ERROR == res.getStatus()) {
            CommonUtils.sendJOSNResponse(response, res);
            return;
        }

        String filePath = String.valueOf(res.getMessage());
        String filename = file.getOriginalFilename();
        
        TbUploadFile uploadFile=new TbUploadFile();
        uploadFile.setDownloadPath(filePath);
        uploadFile.setOriginalName(filename);
        uploadFile.setIdOfTbMerchantUser(joinuserid);
        uploadFile.setUploadOperator(String.valueOf(joinuserid));
        uploadFile.setFileType(fileType.name());
        uploadFile.setStatus(IConstDef.UPLOADSTATUS_COMMITED);
        tbUploadFileService.insert(uploadFile);
        
        
        
		Dict dict=new Dict();
		dict.setLabel(sessionUser.getMchName());
		dict.setUpdateDate(new Date());
		dict.setCreateDate(dict.getUpdateDate());
		dict.setCreateBy(new User(joinuserid));
		dict.setUpdateBy(dict.getCreateBy());
		dict.setType("renew");
		dict.setDelFlag(BaseEntity.DEL_FLAG_AUDIT);
		//续签类型的唯一标示
		dict.setValue(renewType);
		//新文件ID
		dict.setSort(uploadFile.getId());
		dict.setDescription(fileType.getDescription());
		dict.setRemarks(fileType.name());
		dict.setParentId(expiredDate);
		
		dictService.insert(dict);
		
		CommonUtils.sendJOSNResponse(response, new Result(Status.OK, filename + "续签申请提交成功！"));
		 
	}
	
	@ResponseBody
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public Result listAll(HttpServletRequest request){
		//TODO:按保理公司
		Dict queryDict=new Dict();
		queryDict.setType("renew");
		queryDict.setDelFlag(BaseEntity.DEL_FLAG_AUDIT);
		
		List<Dict> ret=dictService.queryList(queryDict);
		
		return new Result(Result.Status.OK,ret);
	}
	
    @RequestMapping(value = "/{id}/download", method = RequestMethod.GET)
    public void downloadSlLoanCommitFile(
            HttpServletRequest request,
            HttpServletResponse response, @PathVariable Integer id) throws IOException {
		
    	Dict dict=dictService.queryById(id);
        TbUploadFile uploadFileVO = tbUploadFileService.queryById(dict.getSort());
		String filename = uploadFileVO.getOriginalName();
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANAPPLY);
    }
	
	@ResponseBody
    @RequestMapping(value = "/{id}/audit", method = RequestMethod.POST)
    public Result audit(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable Integer id ,
            String expiredDate){
		
		Long diff=0L;
		try{
			 diff=TimeUtils.getDateSpaceOfDay(expiredDate);
		}catch(Exception e){
		}
		
		if(diff>=0){
			return new Result(Result.Status.WARNING,String.format("有效期值%s 无效",expiredDate));
		}
		
		int loginUserId=CommonUtils.getLoginUserId();
		
		Dict dict=dictService.queryById(id);
		RenewTypeDesc renewType=RenewTypeDesc.valueOf(dict.getRemarks());
		
		LogUtils.info(log, "审核 %s %s",renewType.getDescription(),dict.getId());
		Map arg=new HashMap();
		arg.put("dictId", dict.getId());
		arg.put("fileId", dict.getSort());
		arg.put("renewType", dict.getValue());
		arg.put("loginUserId", loginUserId);
		arg.put("expiredDate", expiredDate);
		arg.put("joinUserId", dict.getCreateBy().getId());
		
		CallBack cb=SpringUtils.getBean(SpringUtils.getBeanName(renewType.getHandle().getName()));
		if(null==cb){
			LogUtils.error(log,String.format("%s 不存在",renewType.getDescription()));
			return new Result(Result.Status.OK,"审核失败");
		}else{
			cb.updateHandle(arg);
		}
		return new Result(Result.Status.OK,"审核成功");
    }
	
	@ResponseBody
    @RequestMapping(value = "/{id}/reject", method = RequestMethod.POST)
    public Result reject(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable Integer id ){
		
		Dict dict=new Dict();
		dict.setId(id);
		dict.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
		dictService.delete(dict);
		
		return new Result(Result.Status.OK,"拒绝成功");
    }
	
}
